package com.itheima.jobs;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.constant.RedisConstant;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;

import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

/**
 * 定时任务：清理垃圾图片
 */
@Component
public class ClearImgJob {
    @Autowired
    private JedisPool jedisPool;
    //清理图片
    public void clearImg(){
        //计算redis中两个集合的差值，获取垃圾图片名称
        Set<String> deleteImgNames = jedisPool.getResource().sdiff(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        if(CollectionUtil.isNotEmpty(deleteImgNames)){
            for (String deleteImgName : deleteImgNames) {
                //删除图片服务器中的图片文件
                QiniuUtils.deleteFileFromQiniu(deleteImgName);
                //删除redis中的数据
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,deleteImgName);
            }
        }
    }
}
